#!/usr/bin/env groovy
import java.util.TimeZone
final def releaseTag = (env.TAG_NAME ?: env.BRANCH_NAME).replace("/", "-")
def createVersion() {
    //return new Date().format('yyyyMMddHHmmss') }
    // 设置时区为 GMT+8 (东八区)
    def beijingTimeZone = TimeZone.getTimeZone("GMT+8")
    // 获取当前时间
    def currentDate = new Date()
    // 设置时区
    def calendar = Calendar.getInstance(beijingTimeZone)
    calendar.time = currentDate
    // 使用指定时区进行格式化
    def formattedDate = calendar.format('yyyyMMddHHmmss')
    return formattedDate
}

def setBranchName() {
    if (env.BRANCH_NAME == 'dev') {
        return 'dev'
    } else if (env.BRANCH_NAME == 'test') {
        return 'sit'
    } else {
        return env.BRANCH_NAME
    }
}

pipeline {
    agent any

    parameters {
        string(name:'TAG_NAME',defaultValue: '',description:'')
    }

    options{
        buildDiscarder(logRotator(daysToKeepStr: '3',numToKeepStr: '10', artifactNumToKeepStr: '1'))
        disableConcurrentBuilds()
    }


    environment {
        branchName = setBranchName()
        DOCKERHUB_NAMESPACE = "nft-${branchName}"
        K8S_NAMESPACE = "nft-${branchName}"
        REGISTRY = 'tt-tcr.tencentcloudcr.com'
        APP_NAME = "nft-asset"
        DOCKER_IMAGE = "$REGISTRY/$DOCKERHUB_NAMESPACE/$APP_NAME:${releaseTag}-$buildtime"
        SONAR_CREDENTIAL_ID = 'sonar-token'
        releaseTag = (env.TAG_NAME ?: env.BRANCH_NAME).replace("/", "-")
        buildtime = createVersion()
    }

    stages {
        stage ('checkout scm') {
            steps {
                checkout(scm)
            }
        }


        stage ('build & push') {
            steps {
                script {
                    withEnv(["APP_NAME=${env.APP_NAME}", "DOCKER_IMAGE =${env.DOCKER_IMAGE}", "BRANCH_NAME = ${env.BRANCH_NAME}"]) {
                        // Build
                        sh "/usr/local/apache-maven-3.9.9/bin/mvn -s /var/jenkins_home/nft-settings.xml clean -U -P ${BRANCH_NAME} package"
                        // Build Docker Image
                        sh "docker login tt-tcr.tencentcloudcr.com --username 100039426791 --password eyJhbGciOiJSUzI1NiIsImtpZCI6Ik5BNlo6QU9MWTpWMkcyOjJLM1Q6Q1ZQUTpXTlRVOlJFUzM6RDZTWjpQWlFWOlpWTTI6REhWRTo0RkZOIn0.eyJvd25lclVpbiI6IjEwMDAzOTQyNjYyMiIsIm9wZXJhdG9yVWluIjoiMTAwMDM5NDI2NzkxIiwidG9rZW5JZCI6ImNzbXJjN3ZrNWwxcjdqZzZ1OWcwIiwiZXhwIjoyMDQ2NDA4OTkxLCJuYmYiOjE3MzEwNDg5OTEsImlhdCI6MTczMTA0ODk5MX0.phNQa04HMxeU5-uIneiSyccDgTaQfmZJBycVL1sCcq6SWOxyMMRMctHd7K62r0rGylJpHJOyMHXKo1fd3-6V-Ozgq6FvJgxHmFoiWYnSkXJdouDCJS_coFzCD0ASgE0yF71QcNwzlBEGvedXVT-0Mj9n3uz10srQkulRNgT2T6UqDIXZN83eByrHwzAvaQupch8mk792YmHcjxfbF0Y2Fq6uBts657SvGz-AbrGr8n4uJgd2fxd42roPoutFigigVOaAtCDQFsqprwiiBP68u43Z8SwdX0GWViJOsSINKluHfpr37siauxINZAm-Yr0Zibv_HfT8UXaAdQLXUdo67w"
                        sh "docker build -f Dockerfile-${branchName} -t ${DOCKER_IMAGE} ."
                        // Push Docker Image
                        // dockerImage.push()
                        sh "docker push ${DOCKER_IMAGE}"
                        // Deploy to TKE
                        sh """
                        envsubst < deployment-${branchName}.yaml | /usr/bin/kubectl --kubeconfig /var/jenkins_home/.kube/config apply -f -
                        """
                    }
                }
            }
        }
    }
        post {
            always {
                cleanWs()
            }

        success {
            script {
                // 清理构建过程中创建的Docker镜像
                sh "docker rmi $DOCKER_IMAGE || true"
            }
        }
        failure {
            script {
                // 清理构建过程中创建的Docker镜像
                sh "docker rmi $DOCKER_IMAGE || true"
            }
        }
    }
}